import { NextRequest, NextResponse } from 'next/server'
import { verifyToken } from '@/lib/auth-service'

export async function GET(request: NextRequest) {
  try {
    // 从cookie或Authorization头中获取token
    let token = request.cookies.get('auth-token')?.value

    // 如果cookie中没有token，尝试从Authorization头获取
    if (!token) {
      const authHeader = request.headers.get('authorization')
      if (authHeader && authHeader.startsWith('Bearer ')) {
        token = authHeader.substring(7)
      }
    }

    if (!token) {
      return NextResponse.json({
        success: false,
        error: '未登录'
      }, { status: 401 })
    }

    // 验证token
    const decoded = verifyToken(token)
    if (!decoded) {
      return NextResponse.json({
        success: false,
        error: '无效的认证令牌'
      }, { status: 401 })
    }

    return NextResponse.json({
      success: true,
      user: decoded
    })
  } catch (error) {
    console.error('获取用户信息API错误:', error)
    return NextResponse.json({
      success: false,
      error: '服务器内部错误'
    }, { status: 500 })
  }
}